import React from 'react';
import {connect} from 'dva/index';
import {Button, DatePicker, Drawer, Form, Input, Popconfirm, Select, Switch, Table, Tabs, Tag} from 'antd';
import styles from '../index.less';


import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalCreateOrEditWork from "./modal/ModalCreateOrEditWork";

import ModalWorkDetail from "./modal/ModalWorkDetail";
import ModalCreateOrEditWorkTimer from "./modal/ModalCreateOrEditWorkTimer";

moment.locale('zh-cn');
const _ = require('lodash');
const table = 'Work';
const title = '工作任务';

@Form.create()
@connect(({user, global, work}) => ({...user, ...global, ...work}))
export default class TimerWorkSetting extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const {userCode, username, isAdmin} = this.getLoginInfo();

    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });

    payload.userCode = userCode;
    payload.createUser = username;
    payload.isAdmin = isAdmin;

    dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    dispatch({
      type: 'work/findWorkTimerMany',
      payload
    });

  }

  getTimerDay = (record) => {
    const {timerMethod, timerDay} = record;
    // console.log('getTimerDay',timerMethod, timerDay);
    if (timerMethod === '每天') {
      return <div>{`每天${moment(timerDay).format('HH')}点`}</div>;
    }
    if (timerMethod === '每周') {
      return <div>{`每周${timerDay}`}</div>;
    }
    if (timerMethod === '每月') {
      return <div>{`每月${moment(timerDay).format('DD')}日`}</div>;
    }
    if (timerMethod === '每年') {
      return <div>{`每年${moment(timerDay).format('MM月DD日')}`}</div>;
    }
  };
  columns = () => {
    const temp = [];
    temp.push(
      {title: '定时任务编码', dataIndex: 'code', key: 'code', width: 180},
      {title: '创建人', dataIndex: 'createUsername', key: 'createUsername'},
      {
        title: '创建时间', dataIndex: 'createdTs', key: 'createdTs',
        render: (value) => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {title: '定时任务名称', dataIndex: 'workName', key: 'workName'},
      {
        title: '是否启用', dataIndex: 'isEnabled', key: 'isEnabled', render: (value, record) => {
          return <Switch checkedChildren="启用" unCheckedChildren="禁用" checked={value} onChange={v => {
          }}></Switch>;
        }
      },
      // {title: '定时类型', dataIndex: 'timerMethod', key: 'timerMethod'},
      {
        title: '开始时间', dataIndex: 'timerDay', key: 'timerDay', render: (value, record) => {
          return this.getTimerDay(record);
        }
      },
      {
        title: '任务时长', dataIndex: 'delayDay', key: 'delayDay', render: (value, record) => {
          return <div>{`${value}天`}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 240, fixed: 'right',
        render: (value, record) => {
          const {code, createUser, timerMethod, isEnded, isAdmin} = record;
          const _record = _.clone(record);
          _record.relationWorkCode = code;
          return (
            <span>
                   {/*{<a style={{marginRight: '6px'}}*/}
                   {/*    onClick={() => {*/}
                   {/*      this.setState({showDetail: true, record});*/}
                   {/*    }}*/}
                   {/*>详情</a>}*/}
              {<a style={{marginRight: '6px'}} disabled={isEnded}
                  onClick={() => this.onCreateOrEdit(record)}
              >编辑</a>}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'work/deleteWorkTimer',
                    payload: {code}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}} disabled={!isAdmin || isEnded}>删除</a>
              </Popconfirm>}

            </span>
          );
        }
      });

    return temp;
  };

  onCreateOrEdit = (record) => {
    const type = record.code ? 'work/updateWorkTimer' : 'work/createWorkTimer';
    const login = this.getLoginInfo();
    ModalView.open(ModalCreateOrEditWorkTimer,
      {
        title,
        width: '1080px'
      }, {
        table, record,
        callback: (payload) => {
          payload.isAdmin = login.isAdmin;
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  render() {
    const {workTimers = [], _notify, form} = this.props;
    const {showDetail, record} = this.state;
    const loginInfo = this.getLoginInfo();
    //  console.log('log info', loginInfo);
    const {userType} = loginInfo;
    if (_notify) {
      notify(_notify);
    }
    const model = this.props[`${table}Model`];

    return (
      <Form className={styles.content}>

        <ViewTitle
          title={`定时任务列表`}
          level={1}
          actions={[
            <Button type="primary" onClick={() => this.onCreateOrEdit({timerMethod: '每天'})}>添加每天任务</Button>,
            <Button type="primary" onClick={() => this.onCreateOrEdit({timerMethod: '每周'})}>添加每周任务</Button>,
            <Button type="primary" onClick={() => this.onCreateOrEdit({timerMethod: '每月'})}>添加每月任务</Button>,
            <Button type="primary" onClick={() => this.onCreateOrEdit({timerMethod: '每年'})}>添加每年任务</Button>

          ]
          }></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {[
            <FormField
              label={'任务编码'}
              name={'code'}
            >
              <Input></Input>
            </FormField>,
            <FormField
              label={'任务名称'}
              name={'workName'}
            >
              <Input></Input>
            </FormField>,

            <FormField
              label={'责任人'}
              name={'workUsername'}
            >
              <Input></Input>
            </FormField>,
            <FormField
              label={'线下人员'}
              name={'offlineMan'}
            >
              <Input></Input>
            </FormField>,
            <FormField
              label={'创建时间'}
              name={'createdTs'}
              initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndMonth()]}
            >
              <DatePicker.RangePicker></DatePicker.RangePicker>
            </FormField>
          ]}
        </SearchForm>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.columns()}
          dataSource={workTimers}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>
        {showDetail && <Drawer
          visible={showDetail}
          title={`工作任务`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          // maskClosable={false}
          onClose={() => {
            this.setState({showDetail: false});
            this.componentDidMount();
          }}
        >
          <ModalWorkDetail
            record={record}
          > </ModalWorkDetail>
        </Drawer>}

      </Form>
    );
  }
}
